package interceptors

import (
	"administrator/app/apputils/tokenutils"
	"errors"
	"fmt"
	"gitee.com/aurora-engine/utils/rep"
	"gitee.com/aurora-engine/web"
	"github.com/golang-jwt/jwt"
	"strings"
)

type TokenInterceptor struct {
}

func (receiver TokenInterceptor) Before(ctx web.Context, handler any) (bool, error) {
	request := ctx.Request()
	get := request.Header.Get("Authorization")
	if get == "" {
		err := errors.New("身份验证失败")
		ctx.Return(rep.Fail(err, "请登录"), err)
		return false, nil
	}
	if strings.HasPrefix(get, "Bearer ") {
		get = get[7:]
	}
	// 解析 token
	parse, err := jwt.Parse(get, func(token *jwt.Token) (any, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); ok {
			return []byte("all"), nil
		}
		return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
	})
	if err != nil {
		ctx.Return(rep.Fail(errors.New("身份验证失败"), err.Error()))
		return false, err
	}
	// 存入上下文
	claims := parse.Claims.(jwt.MapClaims)
	ctx["token"] = &tokenutils.Token{
		ID: int(claims["ID"].(float64)),
	}
	return true, nil
}

func (receiver TokenInterceptor) Complete(ctx web.Context, handler any) error {

	return nil
}

func (receiver TokenInterceptor) After(ctx web.Context, handler any) error {

	return nil
}
